<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '优惠券发放明细' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
  data_ini:{
    type: [],
    category_id:[],
    cdp_type:[]
  },
  select_customers:[],
  search_loading:false
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '优惠券发放明细',
  initForm: {},
  doCreate: api.createCouponUse,
  doUpdate: api.updateCouponUse,
  doDelete: api.deleteCouponUse,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
  get_drug_all()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '客户姓名',
    key: 'user_name',
    width: 80,
    align: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NButton, {
          size: "small",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.user_name)
        })]
      )

    },
  },
  {
    title: '优惠券名',
    key: 'coupon_title',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '来源订单id',
    key: 'order_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '面值',
    key: 'price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  //   {
  //   title: '来源',
  //   key: 'come',
  //   width:100,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
  {
    title: '过期时间',
    key: 'expred_at',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.expred_at })
    },
  },
    {
    title: '创建人',
    key: 'created_name',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '使用状态',
    key: 'states_name',
    width:100,
    align: 'center',
    render(row) {
      if(row.states === 1){
        return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.states_name })
      }else{
        return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.states_name })
      }

    },
  }, {
    title: '使用订单号',
    key: 'order_id_use',
    width:100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        // h(
        //   NPopconfirm,
        //   {
        //     onPositiveClick: () => handleDelete({ id: row.id }, false),
        //     onNegativeClick: () => {},
        //   },
        //   {
        //     trigger: () =>
        //       withDirectives(
        //         h(
        //           NButton,
        //           {
        //             size: 'small',
        //             type: 'error',
        //           },
        //           {
        //             default: () => '删除',
        //             icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
        //           }
        //         ),
        //         []
        //       ),
        //     default: () => h('div', {}, '确定删除该数据吗?'),
        //   }
        // ),
      ]
    },
  },
]

function search_customer(query){
  data.search_loading = true
  api.getCustomers({keyword:query}).then((res) => {
     data.select_customers = res.data.items
     data.search_loading = false
  })
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}


function on_add(){
  handleAdd()
}

function on_edit(row){
  handleEdit(row)
}

function get_drug_all(){
  if(data.goods_all.length===0){
    api.getCouponAll().then((res) => (data.goods_all = res.data))
  }
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />发放
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getCouponUseList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="选择客户" :label-width="80">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="输入姓名/病历号/手机号搜索"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

<!--            <QueryBarItem label="卡券名称" :label-width="80">-->
<!--              <n-select-->
<!--                    v-model:value="queryItems.coupon_id"-->
<!--                    :options="data.goods_all"-->
<!--                    placeholder="选择卡券"-->
<!--                    label-field="name"-->
<!--                    value-field="id"-->
<!--                    clearable-->
<!--                    @keypress.enter="$table?.handleSearch()"-->
<!--                  />-->
<!--            </QueryBarItem>-->

            <QueryBarItem label="选择卡券" :label-width="80">
              <NSelect
                v-model:value="queryItems.coupon_id"
                style="width: 150px"
                :options="data.goods_all"
                clearable
                label-field="name"
                    value-field="id"
                placeholder="选择卡券"
              />
            </QueryBarItem>



          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >


                <NFormItem label="选择客户" path="user_id" v-if="modalAction==='add'">
                <NSelect
                    v-model:value="modalForm.user_id"
                    :options="data.select_customers"
                    placeholder="输入姓名/病历号/手机号搜索"
                    filterable
                    label-field="all_name"
                    value-field="user_id"
                    style="width: 100%"
                    :loading="data.search_loading"
                    remote
                    clearable
                    @search="search_customer"
                  />
              </NFormItem>
                <NFormItem label="选择卡券" path="coupon_id">
                  <n-select
                    v-model:value="modalForm.coupon_id"
                    :options="data.goods_all"
                    placeholder="选择卡券"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="来源单号" path="order_id">
                  <NInput v-model:value="modalForm.order_id" clearable placeholder="生成订单id" />
                </NFormItem>
                <NFormItem label="面值" path="price">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.price" placeholder="请输入价格" />
                </NFormItem>
                 <NFormItem label="过期时间" path="expred_at">
                   <n-date-picker
                    v-model:formatted-value="modalForm.expred_at"
                    type="datetime"
                    clearable
                    placeholder="请输入过期时间"
                    style="width: 100%"
                  />
                </NFormItem>

                 <NFormItem label="来源" path="come">
                  <NInput style="width: 100%"   v-model:value="modalForm.come" placeholder="请输入来源" />
                </NFormItem>

                <NFormItem label="使用状态" path="states">
                  <NSwitch
                    v-model:value="modalForm.states"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </NFormItem>
                 <NFormItem label="使用单号" path="order_id_use">
                  <NInput type="textarea" v-model:value="modalForm.order_id_use" clearable placeholder="使用订单id" />
                </NFormItem>


          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
